/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentField;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentField;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.service.core.ContentFieldManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentFieldForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * <p>Exposes bean to request to view its properties on JSP page (content field
 * is to be viewed)
 * </p>
 * <p><a href="ViewContentFieldAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.31 $ $Date: 2008/04/29 17:48:05 $
 * @struts.action path="/core/contentField/view"
 * name="contentFieldForm"
 * scope="request"
 * validate="false"
 * roles="core-contentField-view"
 * @struts.action-forward name="viewContentField"
 * path=".core.contentField.view"
 * @struts.action-forward name="listContentFields"
 * path="/core/contentField/list.do"
 * redirect="false"
 */
public final class ViewContentFieldAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		ContentFieldForm contentFieldForm = (ContentFieldForm) form;

		// Check whether it's view of field or choice of locales to edit field
		String redirectUrl = request.getParameter("redirectUrl");
		if ( !GenericValidator.isBlankOrNull(redirectUrl) ) {
			// It's just a choice
			request.getSession().setAttribute(WebappConstants.REDIRECT_URL_KEY, redirectUrl);
		} else if ( !GenericValidator.isBlankOrNull(contentFieldForm.getOwnerId()) ) {
			// It's a view
			request.getSession().removeAttribute(WebappConstants.REDIRECT_URL_KEY);
		} else {
			// That can be any of two
		}

		Long contentFieldId;
		if ( !GenericValidator.isBlankOrNull(contentFieldForm.getId()) ) {
			contentFieldId = Long.valueOf(contentFieldForm.getId());
		} else if ( request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_ID_KEY) != null ) {
			contentFieldId = (Long) request.getSession().getAttribute(WebappConstants.CONTENT_FIELD_ID_KEY);
		} else {

			Long ownerId;
			if ( contentFieldForm.getOwnerId() != null && contentFieldForm.getOwnerId().length() > 0 ) {
				ownerId = Long.valueOf(contentFieldForm.getOwnerId());
			} else {
				if ( log.isWarnEnabled() ) {
					log.warn("Missing owner ID. Returning to index...");
				}
				return mapping.findForward("admin");
			}

			request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

			if ( log.isWarnEnabled() ) {
				log.warn("Missing content field ID. Returning to list...");
			}

			return mapping.findForward("listContentFields");
		}

		ContentFieldManager contentFieldManager = (ContentFieldManager) getBean(Constants.CONTENT_FIELD_MANAGER_BEAN);
		ContentField contentField = contentFieldManager.retrieveContentField(contentFieldId);
		if ( contentField == null ) {
			// content field not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("contentFieldNotFound", new ActionMessage("core.contentField.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listContentFields");
		}

		String fieldIdentifier = contentField.getIdentifier();
		int k = fieldIdentifier.indexOf('[');
		String index = null;
		if ( k != -1 ) {
			index = fieldIdentifier.substring(k + 1, fieldIdentifier.indexOf(']', k));
			fieldIdentifier = fieldIdentifier.substring(0, k);
			contentFieldForm.setIdentifier(fieldIdentifier);
			contentFieldForm.setIndex(index);
		}

		// create a marker
		List contentFieldValues = contentField.getContentFieldValues();
		int cfvSize = contentFieldValues == null ? 0 : contentFieldValues.size();

		Collection contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
		int clSize = contentLocales == null ? 0 : contentLocales.size();

		if ( cfvSize == clSize ) {
			request.setAttribute("isCFVCreate", Boolean.FALSE);
		} else {
			request.setAttribute("isCFVCreate", Boolean.TRUE);
		}

		request.setAttribute("contentField", contentField);

		// get information about owner
		Localizable owner = contentField.getOwner();
		String ownerInfo = WebappUtil.getLocalizableInfo(owner, request);
		request.getSession().setAttribute(WebappConstants.OWNER_INFO_KEY, ownerInfo);

		boolean canUpdateCF = request.isUserInRole("core-contentField-update");
        boolean canUpdateOverridenCF = request.isUserInRole("core-contentField-updateOverriden");
        boolean canUpdateIndexedCF = request.isUserInRole("core-contentField-updateIndexed");
		boolean allowedIndexedField = index != null && !index.equalsIgnoreCase("0");

        Set identifiers = WebappUtil.getOverridableFieldIdentifiers(owner, request);
        boolean overridenField = identifiers.contains(fieldIdentifier);

		if ( canUpdateCF || (owner instanceof ContentPage && canUpdateOverridenCF) || (owner instanceof ActionPage && canUpdateOverridenCF && overridenField) || (owner instanceof Layout && ((canUpdateIndexedCF && allowedIndexedField) || (canUpdateOverridenCF && overridenField))) ) {
			request.setAttribute("updateAllowed", "true");
		}

        saveToken(request);
		return mapping.findForward("viewContentField");
	}
}